<html>
	<head>
         <meta  charset="utf-8" />
         <title>New Graph</title>
        <script src="jquery-1.9.0.min.js" type="text/javascript"></script>
		<script src="sigma.min.js" type="text/javascript"></script>
        <script src="testInputGraph.js" type="text/javascript"></script>
        <script src="jsonlint.js" type="text/javascript"></script>        
		
        <script>
		
		function getLayout(data)
		{
			var nodeCount = data.nodes.length;
			var intermediateNodes = new Array();
			for(var i = 0; i < nodeCount; i++)
			{
				var node = {};
				node.id = data.nodes[i].id;
				node.name = data.nodes[i].name;
				node.x = 0;
				node.y = 0;
				
				intermediateNodes.push(node);
			}		
			
			var sqrt = Math.sqrt(nodeCount);
			var numRows = Math.floor(sqrt);
			var numCols = Math.ceil(sqrt);
			
			if(numRows*numCols < nodeCount)
			{
				numRows++;
			}
			
			var xInc = 0.15;
			var yInc = 0.15;
			var idx = 0;
			
			for(var i = 0; i < numRows; i++){
				for(var j = 0; j < numCols; j++){
					idx = i*numCols + j;
					if(idx >= nodeCount) 
						break;
					var node = intermediateNodes[idx];
					node.x = xInc*(j+1);
					node.y = yInc*(i+1);
				}
			}
			
			data.nodes = intermediateNodes;
		}

		window.onload = function () {
			/* Cleare the text area content*/
			$("#textJson").val("");
		
		    var sigNode = document.getElementById("graph");
		    var sigInst = sigma.init(sigNode).drawingProperties({
		        defaultLabelColor: '#ccc',
		        font: 'Arial',
		        edgeColor: 'source',
		        defaultEdgeType: 'curve'
		    }).graphProperties({
		        minNodeSize: 1,
		        maxNodeSize: 10
		    });


		    $("#textJson").keydown(function (e) {
		        if (e.keyCode === 9) { // tab was pressed
		            // get caret position/selection
		            var start = this.selectionStart;
		            var end = this.selectionEnd;

		            var $this = $(this);
		            var value = $this.val();

		            // set textarea value to: text before caret + tab + text after caret
		            $this.val(value.substring(0, start)
                    + "\t"
                    + value.substring(end));

		            // put caret at right position again (add one for the tab)
		            this.selectionStart = this.selectionEnd = start + 1;

		            // prevent the focus lose
		            e.preventDefault();
		        }
		    });

		    function onClickViewGraph() {
		    	if($("#textJson").val().length == 0)
		    	{
		    		alert("Graph description is empty\n Please input it.");
		    		return false;
		    	}
		    
		        try {
		            sigInst.emptyGraph();
		            var jsonData = {};
		            try {
		                jsonData = eval('(' + $("#textJson").val() + ')');
		                var testGraph = new testInputGraph(jsonData);
		                if (!testGraph.test()) {
		                    return false;
		                }
		            }
		            catch (err) {
		                var tmpStr = $("#textJson").val();
		                jsonlint.parse(tmpStr.replace(/\t/g,""));
		            }

		            getLayout(jsonData);
		            for (var i = 0; jsonData.nodes != undefined && i < jsonData.nodes.length; i++) {
		                sigInst.addNode(jsonData.nodes[i].id, {
		                    label: jsonData.nodes[i].name,
		                    color: jsonData.nodes[i].color != undefined ? jsonData.nodes[i].color : "#ff0000",
		                    x: jsonData.nodes[i].x,
		                    y: jsonData.nodes[i].y
		                });
		            }

		            for (var i = 0; jsonData.edges != undefined && i < jsonData.edges.length; i++) {
		                sigInst.addEdge(jsonData.edges[i].name, jsonData.edges[i].from, jsonData.edges[i].to);
		            }

		            sigInst.draw();
		            
		        }
		        catch (err) {
		            alert(err);
		            return false;
		        }
		        return true;
		    }

		    $("#viewgraph").click(onClickViewGraph);

		    $("#savebtn").click(function (e) {
				
		        if (!onClickViewGraph()) {
		            return;
		        }
                
		        var btn = this;
		        btn.disabled = true;
		        var jsonData;
		        try {
		            jsonData = eval('(' + $("#textJson").val() + ')');

		            //test data input
		            if (jsonData.name != undefined && jsonData.name != "") {
		                $.post("http://localhost:8080/RESTfulExample/rest/graph/post/graphname=" + jsonData.name + "&graphdescription=" + escape($("#textJson").val())).done(function (result) {
		                    var jsonResult = eval('(' + result.jsonmapper["@json"] + ')');
		                    alert(jsonResult.method + ": " + jsonResult.value);
		                    btn.disabled = false;
		                }).fail(function (err) {
		                    alert(err);
		                    btn.disabled = false;
		                });
		            }
		            else {
		                alert("PLease! Input a name for this graph.");
		                btn.disabled = false;
		            }
		        }
		        catch (err) {
		            alert(err);
		            btn.disabled = false;
		        }

		    });

		}

		    
			
		</script>
	</head>
	<body>
        <div id="">
            
            <div id="jsontab" style="float:left; width:40%; height: 500px">
                <div style="padding:10px">
                    <div style="width:100%">
                        <div style="float:left">Graph Json: </div>
                    </div>
                    <div>
                        <textarea id="textJson" style="width:100%; height: 430px;" wrap="off"></textarea>
                    </div>
                    <div>
                        <div style="float:right">
                            <button id="viewgraph" style="margin:5px">View Graph</button>
                        </div>

                        <div style="float:right">
                            <button id="savebtn" style="margin:5px">Save Graph</button>
                        </div>

                    </div>
                </div>
            </div>
		    
            <div id="graphtab" style="float:left; width: 60%; height:500px">
                <div id="graph" style="margin:30px 10px 40px 10px;background-color:Black; height:430px"></div>
            </div>
	    </div>
    </body>
</html>